package priv.mill.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import priv.mill.server.ToolServer;

public class ErfenServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String code = req.getParameter("code");
		resp.setHeader("Access-Control-Allow-Origin", "*");
		PrintWriter writer = resp.getWriter();
		if(code.contains("import")) {
			writer.print("error");
			return;
		}
		long[] arr = getArray();
		int index = (int) (Math.random() * arr.length);
		try {
			int result = getObject("  package priv.mill.servlet;\n"+code, arr, arr[index]);
			System.out.printf("搜索的位置在%d，找到的位置在%d\n",index,result);
			if (result == index) {
				writer.print("success");
			} else {
				writer.print("error");
			}
		} catch (Exception e) {
			writer.print(e.getMessage());
		}

	}

	private int getObject(String code, long[] arr, long l) throws NoSuchMethodException, SecurityException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		// Method method = obj.getClass().getMethod("search", long[].class,long.class);
		Class<?> compile = ToolServer.compile("priv.mill.servlet.SearchDemo", code);
		Method method = compile.getMethod("search", long[].class, long.class);
		Object invoke = method.invoke(null, arr, l);
		return (Integer) invoke;
	}

	private long[] getArray() {
		Set<Long> list = new HashSet<Long>();
		while (true) {
			list.add((long) (Math.random() * 10000));
			if (list.size() >= 100)
				break;
		}
		Object[] array = list.toArray();
		Arrays.sort(array);
		long[] arr = new long[array.length];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = (Long) (array[i]);
		}
		return arr;
	}

	public static void main(String[] args) throws ServletException, IOException {
		ErfenServlet erfenServlet = new ErfenServlet();
		erfenServlet.doPost(null, null);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

}
